package formula.web;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import org.slf4j.LoggerFactory;

import twork.util.basic.ArrayWithTotalList;
import formula.business.dao.DriverDao;
import formula.business.model.Driver;

@SuppressWarnings("serial")
@ManagedBean
@ViewScoped
public class DriversHome implements Serializable {

	public static final String EL_NAME = "#{driversHome}";
	private final org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());

	//
	@ManagedProperty(value = "#{driverDao}")
	private DriverDao driverDao;
	//
	@ManagedProperty(value = "#{driverFilterForm}")
	DriverFilterForm driverFilterForm;
	//
	private LazyDataModel<Driver> drivers;

	public void clearDriverForm() {
		this.driverFilterForm.clear();
	}

	@SuppressWarnings({ "unused" })
	@PostConstruct
	private void init() {
		drivers = new LazyDataModel<Driver>() {

			@Override
			public List<Driver> load(int first, int pageSize, String sortField, SortOrder sortOrder,
					Map<String, String> filters) {
				driverFilterForm.setFirstResult(first);
				driverFilterForm.setPageSize(pageSize);
				driverFilterForm.setSortColumnName(sortField);
				Boolean b = null;
				if (sortOrder == SortOrder.ASCENDING) {
					b = Boolean.TRUE;
				} else if (sortOrder == SortOrder.DESCENDING) {
					b = Boolean.FALSE;
				}
				driverFilterForm.setSortAscending(b);
				ArrayWithTotalList<Driver> list = driverDao.searchAndCountDrivers(driverFilterForm
						.extractDriverFilter());
				int count = list.getTotalCount();
				drivers.setRowCount(count);
				logger.debug("count = {}", count);
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("LazyModel INVOKE"));
				return list;
			}
		};
	}

	public LazyDataModel<Driver> getDrivers() {
		return drivers;
	}

	public void setDriverDao(DriverDao driverDao) {
		this.driverDao = driverDao;
	}

	public void setDriverFilterForm(DriverFilterForm driverFilterForm) {
		this.driverFilterForm = driverFilterForm;
	}
}
